package com.best.intelligentTrolley.utils

import android.content.Context
import android.os.Environment
import java.io.DataOutputStream
import java.io.IOException
import java.math.BigInteger
import java.util.regex.Matcher
import java.util.regex.Pattern

/**
 * author: shihao
 * date: 2021/2/5 11:40
 * description:
 */
object CommonUtils {

    fun requestRootPermission(context: Context): Boolean {
        var process: Process? = null
        var os: DataOutputStream? = null
        try {
            val cmd = "chmod 777 ${context.packageCodePath}"
            process = Runtime.getRuntime().exec("su") //切换到root帐号
            os = DataOutputStream(process.outputStream)
            os.writeBytes("$cmd\n")
            os.writeBytes("exit\n")
            os.flush()
            process.waitFor()
        } catch (e: Exception) {
            return false
        } finally {
            try {
                os?.close()
                process?.destroy()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        return true
    }

    /**
     * 设置系统时间
     * //测试的设置的时间【时间格式 yyyyMMdd.HHmmss】
     */
    fun setSystemDate(dateTime: String) {
        try {
            val process = Runtime.getRuntime().exec("su")
            val os = DataOutputStream(process.outputStream)
            os.writeBytes("setprop persist.sys.timezone GMT\n")
            os.writeBytes("/system/bin/date -s $dateTime\n")
            os.writeBytes("clock -w\n")
            os.writeBytes("exit\n")
            os.flush()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    /**
     * 创建授权码
     *  @param factoryNo 机器编号
     */
    fun createAuthorizationCode(factoryNo: String): String? {
        val k = "HKBT"
        var x = 0
        for (element in factoryNo) {
            val ch = element.toInt()
            x += ch
        }
        val n = BigInteger(1, k.toByteArray())
        return Integer.toHexString(x * n.toString().toInt())
    }

    fun getDeviceModelCode(): String {
        return "0x36"
    }



    /**
     * 获取公共的缓存目录
     */
    fun getCacheFolder(): String {
        return Environment.getExternalStorageDirectory().path + "/SpaceSterilizer/"
    }

    /***
     * 匹配字符串中有多少个相同的字符
     */
    fun matchingStringCount(data: String, match: String): Int {
        val r: Pattern = Pattern.compile(match)
        val m: Matcher = r.matcher(data)
        var count = 0
        while (m.find()) {
            count++
        }
        return count
    }


}